#include "MsgUtil.h"
#include <pthread.h>
#include <stdio.h>
#include <glib.h>
#include "sendConfigRequest.h"
#include "sendHeartRequest.h"

//装网关ip和sn
char* gatewayIp;
char* sn;

char* getGatewayIp(){
    if (gatewayIp!=NULL)
    {
        return gatewayIp;
    }
    GKeyFile *file = g_key_file_new();
    g_key_file_load_from_file(file,"../config/config.ini",G_KEY_FILE_NONE,NULL);
    gchar* path = g_key_file_get_string(file,"config","deviceInfoPath",NULL);


    GKeyFile *keyFile = g_key_file_new();
    g_key_file_load_from_file(keyFile,path,G_KEY_FILE_NONE,NULL);
    gatewayIp = g_key_file_get_string(keyFile,"config","gatewayIp",NULL);

    g_key_file_free(keyFile);
    g_key_file_free(file);
    return gatewayIp;
}

char* getsn(){
    if (sn!=NULL)
    {
        return sn;
    }
    sn="147258369";
    g_print("sn=%s\n",sn);
    return sn;
}

void* recvConfigMsg(void *param){
    while (1)
    {
        //接收配置信息
        int mqId=getMsgQueue();
        if (mqId==-1)
        {
            printf("mq create fail\n");
            pthread_exit(NULL);
        }
        
        // Message msg={
        //     .type=1
        // };
        Message msg;
        msg.type=1;

        int ret=recvMsg(mqId,&msg,MSG_SIZE);
        if (ret==-1)
        {
            printf("recv data fail\n");
            pthread_exit(NULL);
        }
        printf("recv data success,type=%ld,text=%s\n",msg.type,msg.text);

        //向网关发起配置请求
        sendConfigRequest(&gatewayIp,getsn());
    }
    
}

int main(int argc, char const *argv[])
{
    printf("start join mainnprocess\n");
    //接收配置信息，向网关进行注册广告机配置信息
    pthread_t tid;
    pthread_create(&tid,NULL,recvConfigMsg,NULL);

    //向网关发起心跳请求
    while (1)
    {
        char* ipTmp=getGatewayIp();
        printf("ipTmp=%s\n",ipTmp);
        if (ipTmp==NULL)
        {
            continue;
        }
        //发起心跳请求
        sendHeartRequest(ipTmp,getsn());
        sleep(2);
    }
    
    return 0;
}
